package IO流.InputStream01;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStream01 {
    public static void main(String[] args) throws FileNotFoundException {
        int readData = 0;
        //FileInputStream构造入参name为文件的路径，每次只读取一个字节，效率较低
        FileInputStream fileInputStream = new FileInputStream("src/main/java/IO流/InputStream01/hello.txt");
        try {
            //每次只读取一个字节
            //如果返回-1，表示读取完毕，如果读取正常，返回实际读取的字节的ASCII码值
            while ((readData = fileInputStream.read()) != -1 ){
                System.out.print((char) readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void FileInputStream02() throws FileNotFoundException {
        //创建一个字节数组
        byte[] buf = new byte[8];
        int readLen = 0;
        FileInputStream fileInputStream = null;
        try {
            //每次只读取一个字节
            fileInputStream = new FileInputStream("src/main/java/IO流/InputStream01/hello.txt");
            //将文件以流的方式读入到字节数组中，并且返回数组的大小，
            //如果返回-1，表示读取完毕，如果读取正常，返回实际读取的字节的大小
            while ((readLen = fileInputStream.read(buf)) != -1 ){
                //new String(buf,0, readLen) 将字节数组转换成字符串
                System.out.print(new String(buf,0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                assert fileInputStream != null;
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
